﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using YT.DB;
using YT.Commons;
using YT.Controls;
using YT.Controls.GridColumn;

namespace YT.XH.MF
{
    public partial class frmmMainQry : Form
    {
        private DBAccess mdbcon = new DBAccess(false, false);
        private TitleType mTitleType =new TitleType() ;
        private string mstrHdrRecID = string.Empty;
        private bool mblnClickExit = false;

        public frmmMainQry()
        {
            InitializeComponent();
        }

        private void frmmMainQry_Load(object sender, EventArgs e)
        {
            this.Text = "查询";
            FillMainGrid();
        }

        private void FillMainGrid()
        {
            string strSQL = string.Empty;
            strSQL = "select * from mQryHdr where QryType='" + mTitleType + "' order by seqno";
            DataTable dtQryHdr = mdbcon.GetDataTable(strSQL);
            if (dtQryHdr.Rows.Count == 0)
                AddNewRow(this.dgvMain );
            else
            {
                foreach (DataRow drRow in dtQryHdr.Rows)
                {
                    this.dgvMain.Rows.Add();
                    this.dgvMain.Rows[this.dgvMain.Rows.Count - 1].Cells[ColName.Index].Value = CvtFunc.ToString(drRow["QryName"]);
                    this.dgvMain.Rows[this.dgvMain.Rows.Count - 1].Cells[ColCreatDate.Index].Value = CvtFunc.ToString(drRow["CreatDate"]);
                    this.dgvMain.Rows[this.dgvMain.Rows.Count - 1].Cells[ColRemark.Index].Value = CvtFunc.ToString(drRow["Remark"]);
                    this.dgvMain.Rows[this.dgvMain.Rows.Count - 1].Cells[ColRecID.Index].Value = CvtFunc.ToString(drRow["RecID"]);
                }
            }
            this.dgvMain.EndEdit();
        }

        private void FillDetail(string strHdrRecID )
        {
            string strSQL = string.Empty;
            strSQL = "select * from mQryDetail where HdrRecID='" + strHdrRecID + "'";
            DataTable dtDtl = mdbcon.GetDataTable(strSQL);
            if (dtDtl.Rows.Count == 0)
            {
                if ( this.dgvDetail.Rows.Count <=0)
                AddNewRow(this.dgvDetail);
            }
            else
            {
                foreach (DataRow drRow in dtDtl.Rows)
                {
                    this.dgvDetail.Rows.Add();
                    this.dgvDetail.Rows[this.dgvDetail.Rows.Count - 1].Cells[ColDetalSeqNo.Index].Value = CvtFunc.ToString(drRow["SeqNo"]);
                    this.dgvDetail.Rows[this.dgvDetail.Rows.Count - 1].Cells[ColDetailTopicType.Index].Value = CvtFunc.ToString(drRow["TopicType"]);
                    this.dgvDetail.Rows[this.dgvDetail.Rows.Count - 1].Cells[ColDetailTitleHdr.Index].Value = CvtFunc.ToString(drRow["Title"]);
                    this.dgvDetail.Rows[this.dgvDetail.Rows.Count - 1].Cells[ColDetailTitle.Index].Value = CvtFunc.ToString(drRow["ColTitle"]);
                    this.dgvDetail.Rows[this.dgvDetail.Rows.Count - 1].Cells[ColDetailAndOr.Index].Value = CvtFunc.ToString(drRow["AndOr"]);
                    this.dgvDetail.Rows[this.dgvDetail.Rows.Count - 1].Cells[ColDetailOpera.Index].Value = CvtFunc.ToString(drRow["OperSign"]);
                    this.dgvDetail.Rows[this.dgvDetail.Rows.Count - 1].Cells[ColDetailData.Index].Value = CvtFunc.ToString(drRow["Result"]);
                }
            }
            this.dgvDetail.EndEdit();
        }

        private bool UpdateHdr()
        {
            string strSQL = string.Empty;
            string strFields = "SeqNo,QryType,QryName,CreatDate,Remark";
            this.dgvMain.EndEdit();
            foreach (DataGridViewRow dgvRow in this.dgvMain.Rows)
            {
                strSQL = "select top 0 * from mQryHdr";
                DataRow drRow = mdbcon.GetDataTable(strSQL ).NewRow ()  ;
                drRow["SeqNo"] = dgvRow.Cells[ColSeqNo.Index].ToString();
                drRow["QryType"] = mTitleType.ToString();
                drRow["CreatDate"] = dgvRow.Cells[ColCreatDate.Index].ToString();
                drRow["Remark"] = dgvRow.Cells[ColRemark.Index].ToString();
                string strRecID =CvtFunc.ToString ( dgvRow.Cells[ColSeqNo.Index] );
                if (CvtFunc.ToDouble(strRecID) <= 0)
                {                    
                    DataFunctions.UpdateTable(mdbcon, strFields, "mQryHdr", drRow,FormStatus.AddNew); 
                }
                else
                {
                    DataFunctions.UpdateTable(mdbcon, strFields, "mQryHdr", drRow, FormStatus.Update  ); 
                }
                dgvRow.Cells[ColRecID.Index].Value = CvtFunc.ToString(drRow["RecID"]);
            }
            return true;
        }

        private bool UpdateDetail()
        {
            string strSQL = string.Empty;
            string strFields = "HdrRecID,SeqNo,TopicType,Title,ColTitle,AndOr,OperSign,Result,Description";
            strSQL = "delete from mQtyDetail where hdrseqno='"+ CvtFunc.ToString ( this.dgvMain.CurrentRow.Cells[ColRecID.Index ].Value )  +"'";
            mdbcon.ExecuteSql(strSQL);
            foreach (DataGridViewRow dgvRow in this.dgvDetail.Rows)
            {
                strSQL = "select top 0 * from mQryDetail";
                DataRow drRow = mdbcon.GetDataTable(strSQL).NewRow();
                drRow["HdrRecID"] = mstrHdrRecID   ;
                drRow["SeqNo"] = CvtFunc.ToString ( dgvRow.Cells[ ColDetalSeqNo.Index ].Value );
                drRow["TopicType"] = CvtFunc.ToString ( dgvRow.Cells[ColDetailTopicType.Index ].Value );   
                drRow["Title"] = CvtFunc.ToString ( dgvRow.Cells[ColDetailTitleHdr.Index].Value ); 
                drRow["ColTitle"] = CvtFunc.ToString ( dgvRow.Cells[ColDetailTitle.Index ].Value ); 
                drRow["AndOr"] = CvtFunc.ToString ( dgvRow.Cells [ ColDetailAndOr.Index ].Value ); 
                drRow["OperSign"] = CvtFunc.ToString ( dgvRow.Cells[ ColDetailOpera .Index ].Value );
                drRow["Result"] = CvtFunc.ToString ( dgvRow.Cells [ ColDetailData.Index ].Value );
                drRow["Description"]=CvtFunc.ToString ( dgvRow.Cells [ ColDetailRemark.Index ].Value );

                DataFunctions.UpdateTable(mdbcon, strFields, "mQryDetail", drRow, FormStatus.AddNew );
            }
            return true;
        }


        private bool DelHdr( DataGridViewRow dgrRow   )
        {
            string strRecID = string.Empty;
            strRecID = CvtFunc.ToString(dgrRow.Cells[ColRecID.Index].ToString());
            if (!DelDetail(CvtFunc.ToString(dgrRow.Cells[ColSeqNo.Index].Value))) return false;
            string strSQL ="Delete from mQryHdr where RecID='"+ strRecID  +"'";
            mdbcon.ExecuteSql(strSQL);
            return true;
        }
        private bool DelDetail(string strRecID)
        {
            string strSQL = string.Empty;
            strSQL = "delete from mQryDetail where RecID='" + strRecID + "'";
            mdbcon.ExecuteSql(strSQL);
            return true;
        }

        private void dgvDetail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 0 && dgvDetail.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((this.dgvDetail.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_Lookup(e.ColumnIndex);
                }
            }
            else
            {
                if (this.dgvDetail.CurrentCell.ColumnIndex == ColDetailDel.Index)
                {
                    if (!this.DelDetail(CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[ColDetailRecID.Index].Value)))
                        return;
                    this.dgvDetail.Rows.Remove(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex]);
                    if (this.dgvDetail.Rows.Count == 0)
                    {
                        AddNewRow(this.dgvDetail);
                    }
                }
            }
        }

        private void Dtl_Lookup( int iColumn )
        {
            frmmQryLookup frmQry = new frmmQryLookup();
            frmQry.StartPosition = FormStartPosition.CenterScreen;
            frmQry.ShowDialog(); 
        }

        private void AddNewRow( DataGridView dgvCon  )
        {

            dgvCon.Rows.Add();
            int intRows = dgvCon.Rows.Count - 1;
            if (dgvCon.Name == this.dgvDetail.Name)
            {
                if (intRows >= 1)
                {
                    dgvCon.Rows[intRows].Cells[ColDetailTitleHdr.Index].Value = dgvDetail.Rows[intRows - 1].Cells[ColDetailTitleHdr.Index];
                    dgvCon.Rows[intRows].Cells[ColDetailTopicType.Index].Value = dgvDetail.Rows[intRows - 1].Cells[ColDetailTopicType.Index];
                }
                else
                {
                    dgvCon.Rows[intRows].Cells[ColDetailTitleHdr.Index].Value = "";
                    dgvCon.Rows[intRows].Cells[ColDetailTopicType.Index].Value = "";
                }

                dgvCon.Rows[intRows].Cells[ColDetailAndOr.Index].Value = "And";
                dgvCon.Rows[intRows].Cells[ColDetailOpera.Index].Value = "";
                dgvCon.Rows[intRows].Cells[ColDetailTitle.Index].Value = "";
                dgvCon.Rows[intRows].Cells[ColDetailRemark.Index].Value = "";
            }
            else if (dgvCon.Name == this.dgvMain.Name)
            {
                dgvCon.Rows[intRows].Cells[ColName.Index ].Value = "";
                dgvCon.Rows[intRows].Cells[ColCreatDate.Index].Value = BaseFunctions.FormatDate ( DateTime.Now.Date.ToString() ,DateFormatOption.DateFmtYMD  ) ;
                dgvCon.Rows[intRows].Cells[ColRemark.Index].Value = "";   
            }
            ResetGridSeqNo(dgvCon );
        }
        


        private void ResetGridSeqNo( DataGridView dgvCon )
        {
            int intSeqNo = 0;
            if (dgvCon.Name == this.dgvDetail.Name)
                intSeqNo = ColDetalSeqNo.Index ;
            else if (dgvCon.Name == this.dgvMain.Name)
                intSeqNo = ColSeqNo.Index ;
            foreach (DataGridViewRow dgvRow in dgvCon.Rows) 
            {
                dgvRow.Cells[intSeqNo].Value = (dgvRow.Index +1).ToString()  ;   
            }
        }

        private void dgvDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private bool  CheckDetailCell(int iColumn,ref string strErrMsg )
        {
            this.dgvDetail.EndEdit();
            string strvalue = CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[iColumn].Value);
            if (iColumn == ColDetailTopicType.Index)
            {
                if (strvalue == "")
                    strErrMsg = "[类别] 不能为空！";
            }
            else if (iColumn == ColDetailTitleHdr.Index)
            {
                if (strvalue == "")
                    strErrMsg = "[标题] 不能为空！";
            }
            else if (iColumn == ColDetailAndOr.Index)
            {
                if (strvalue == "")
                    strErrMsg = "[条件关系] 不能为空！";
            }
            else if (iColumn == ColDetailOpera.Index)
            {
                if (strvalue == "")
                    strErrMsg = "[比较条件] 不能为空！";
            }

            if (strErrMsg != "") return false;
            return true;
        }

        private bool CheckDetailRow( DataGridViewRow dgvRow,ref  string strErrMsg )
        {           
            foreach (DataGridViewCell dgvCell in dgvRow.Cells)
            {
                if (!CheckDetailCell(dgvCell.ColumnIndex,ref  strErrMsg)) break;
            }
            if (strErrMsg == "") return true;
            return false;            
        }


        private void dgvDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

        }

        private void frmmMainQry_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.mdbcon.CloseCon();
        }

        private void dgvMain_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if ( this.dgvMain.CurrentCell ==null ) return ;
            string strRecID = CvtFunc.ToString(dgvMain.CurrentRow.Cells[ColRecID.Index].Value);
            FillDetail(strRecID);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string strErrMsg =string.Empty ;
            if (!UpdateHdr()) return;
            if (CheckDetailRow(this.dgvDetail.CurrentRow,ref  strErrMsg))
            {
                if (!UpdateDetail()) return;
            }
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvDetail_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (mblnClickExit) return;
            string strErrMsg = string.Empty;
            DataGridViewRow drvRow = this.dgvDetail.CurrentRow;
            if (drvRow == null) return;
            e.Cancel = CheckDetailRow(drvRow,ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
           
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
        }

        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            bool blnRet = false;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }
            else if (this.dgvMain != null && BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvMain.Name))
            {
                //blnRet = dgTerm_KeyDownEvent(keyData);
            }
            else if (this.dgvDetail != null && BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvDetail.Name))
            {
                blnRet = dgvDetail_KeyDownEvent(keyData);
            }
            if (!blnRet)
            {
                return MainProcessCmdKey(ref msg, keyData);
            }
            return true ;
            
        }

        private bool MainProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;

            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }            
            return false;
        }

        private void dgvDetail_KeyDown(object sender, KeyEventArgs e)
        {
            string strErrMsg = string.Empty;
            if (e.KeyData == Keys.Return)
            {
                this.dgvDetail.EndEdit();
                int j = ColDetailData.Index;
                if (dgvDetail.CurrentCell.ColumnIndex == j)
                {

                    if (CheckDetailRow(this.dgvDetail.CurrentRow, ref strErrMsg))
                    {
                        if (!UpdateDetail()) return;
                    }
                    else
                    {
                        MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }

                    if (dgvDetail.CurrentCell.RowIndex < dgvDetail.Rows.Count - 1)
                    {
                        dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex + 1].Cells[ColDetailTopicType.Index];
                    }
                    else
                    {
                        AddNewRow(this.dgvDetail);
                        dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex + 1].Cells[ColDetailTopicType.Index];
                    }
                }
                else
                {
                    j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvDetail, dgvDetail.CurrentCell.ColumnIndex);
                    if (j >= 0) dgvDetail.CurrentCell = dgvDetail.CurrentRow.Cells[j];
                }

            }
        }



        private bool dgvDetail_KeyDownEvent(Keys keydata)
        {
            string strErrMsg = string.Empty;
            switch (keydata)
            {
                case Keys.Return:
                    this.dgvDetail.EndEdit();
                    int j = ColDetailData.Index;
                    if (dgvDetail.CurrentCell.ColumnIndex == j)
                    {

                        if (CheckDetailRow(this.dgvDetail.CurrentRow, ref strErrMsg))
                        {
                            if (!UpdateDetail()) return true;
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }

                        if (dgvDetail.CurrentCell.RowIndex < dgvDetail.Rows.Count - 1)
                        {
                            dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex + 1].Cells[ColDetailTopicType.Index];
                        }
                        else
                        {

                            AddNewRow(this.dgvDetail);
                            dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex + 1].Cells[ColDetailTopicType.Index];

                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvDetail, dgvDetail.CurrentCell.ColumnIndex);
                        if (j >= 0) dgvDetail.CurrentCell = dgvDetail.CurrentRow.Cells[j];
                    }

                    
                    return true;
            }
            
            return false ;
        }

        private void dgvMain_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            string strRecID = CvtFunc.ToString(dgvMain.CurrentRow.Cells[ColRecID.Index].Value);
            FillDetail(strRecID);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            mblnClickExit = true;
            string strErrMsg = string.Empty;
            if (MessageBox.Show("是否保存？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (!UpdateHdr()) return;
                if (CheckDetailRow(this.dgvDetail.CurrentRow, ref  strErrMsg))
                {
                    if (!UpdateDetail()) return;
                }
                if (strErrMsg != "")
                {
                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                this.Close();
            }
        }

        private void dgvDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            if (this.dgvDetail.CurrentCell.ColumnIndex == ColDetailTopicType.Index)
            {
                DataGridViewComboBoxEditingControl dgvCombox = e.Control as DataGridViewComboBoxEditingControl;
                if (mTitleType == TitleType.SuddenDeafness)
                {
                    //基础资料
                    //病史调查
                    //治疗前检查
                    //疗效评估
                    //治疗结束后综合疗效评估
                    //治疗后不良反应报告
                    dgvCombox.Items.Clear();
                    dgvCombox.Items.Add("基础资料");
                    dgvCombox.Items.Add("病史调查");
                    dgvCombox.Items.Add("治疗前检查");
                    dgvCombox.Items.Add("疗效评估--第7天");
                    dgvCombox.Items.Add("疗效评估--第14天");
                    dgvCombox.Items.Add("疗效评估--第28天");
                    dgvCombox.Items.Add("疗效评估--更多评估");
                    dgvCombox.Items.Add("治疗结束后综合疗效评估");
                    dgvCombox.Items.Add("治疗后不良反应报告");
                }
                else if ( mTitleType == TitleType.Dizziness  )
                {
                    //基础资料
                    //病史调查
                    //治疗前检查
                    //疗效评估
                    //治疗结束后综合疗效评估
                    //治疗后不良反应报告
                    dgvCombox.Items.Clear();
                    dgvCombox.Items.Add("基础资料");
                    dgvCombox.Items.Add("病史调查");
                    dgvCombox.Items.Add("治疗前检查");
                    dgvCombox.Items.Add("疗效评估--第1周");
                    dgvCombox.Items.Add("疗效评估--第2周");
                    dgvCombox.Items.Add("疗效评估--第1月");
                    dgvCombox.Items.Add("疗效评估--第3月");
                    dgvCombox.Items.Add("疗效评估--第6月");
                    dgvCombox.Items.Add("疗效评估--更多评估");
                    dgvCombox.Items.Add("治疗结束后综合疗效评估");
                    dgvCombox.Items.Add("治疗后不良反应报告");
                }
                else if ( mTitleType == TitleType.MeniereDisease )
                {
                    //基础资料
                    //病史调查
                    //治疗前检查
                    //疗效评估
                    //治疗结束后综合疗效评估
                    //治疗后不良反应报告
                    dgvCombox.Items.Clear();
                    dgvCombox.Items.Add("基础资料");
                    dgvCombox.Items.Add("病史调查");
                    dgvCombox.Items.Add("治疗前检查");
                    dgvCombox.Items.Add("疗效评估--第1月");
                    dgvCombox.Items.Add("疗效评估--第3月");
                    dgvCombox.Items.Add("疗效评估--第6月");
                    dgvCombox.Items.Add("疗效评估--第12月");
                    dgvCombox.Items.Add("疗效评估--第24月");
                    dgvCombox.Items.Add("疗效评估--更多评估");
                    dgvCombox.Items.Add("治疗结束后综合疗效评估");
                    dgvCombox.Items.Add("治疗后不良反应报告");
                }
                else if (mTitleType == TitleType.OTHERS)
                {

                }
            }
        }

        private void tbcMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.dgvMain.CurrentCell == null) return;
            string strRecID = CvtFunc.ToString(dgvMain.CurrentRow.Cells[ColRecID.Index].Value);
            FillDetail(strRecID);
        }
    }
}
